<?php

namespace app\controller\admin;


use think\Request;
use think\facade\Validate;
use app\eslib\EsUtils;
use app\model\EcCategoryModel;
use app\model\EcSpecificationModel;
use app\model\ModelUtils;
use think\facade\Cache;

class EcSpecification
{

    /**
     * 构造方法
     */
    public function __construct()
    {
        // $this->middleware('jwtauth.admin');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        // 查询 KV 数据
        $mode = $request->param('_mode', '');
        $categoryId = intval($request->param('category_id', 0));
        if ($mode == 'dict') {
            return json(EsUtils::stdmessage(1, '', EcSpecificationModel::getDictData($categoryId)));
        }
        if ($mode == 'tree') {
            return json(EsUtils::stdmessage(1, '', EcSpecificationModel::getTreeList($categoryId)));
        }

        // 查询列表数据
        $searchText = $request->param('search_text', '');
        $page = intval($request->param('page', 1));
        $pageSize = intval($request->param('page_size', 10));
        $cacheKey = EsUtils::shortMD5("ec_specification_index_{$page}_{$pageSize}_{$searchText}_{$categoryId}");
        $data = Cache::get($cacheKey);
        if (!$data) {
            if ($categoryId || $searchText) {
                $data = EcSpecificationModel::dbView()->where(function ($query) use ($categoryId, $searchText) {
                    if ($categoryId > 0) {
                        $query->where('category_id', $categoryId);
                    }
                    if ($searchText) {
                        $query->where(function ($query) use ($searchText) {
                            $query->where('id', intval($searchText))->whereOr('spec_name', 'like', "%{$searchText}%");
                        });
                    }
                })->paginate($pageSize);
            } else {
                $data = EcSpecificationModel::getTreeRows($categoryId);
                $data = ['total' => count($data), 'data' => EsUtils::arrayPaginate($data, $page, $pageSize)];
            }
            Cache::set($cacheKey, $data, 10);
            ModelUtils::cachePut('ec_specification', $cacheKey);
        }
        return json(EsUtils::stdmessage(1, '', $data));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $formData = $request->all();
        $validator = Validate::rule([
            'pid' => 'required|numeric',
            'category_name' => 'required|max:150',
            'icon' => 'max:150',
        ], [
            'required' => ':attribute 必须填写',
            'numeric' => ':attribute 必须是数值',
            'max' => ':attribute 不能超过 :max 个字符',
        ], [
            'pid' => '上级类别',
            'category_name' => '类别名称',
            'icon' => '类别图片'
        ]);
        if (!$validator->check($formData)) {
        return json(EsUtils::stdmessage(0, $validator->getError()));
}
        // 表单数据处理
        // ...
        try {
            $model = EcSpecificationModel::create($formData);
            return json(EsUtils::stdmessage(1, '', $model->id));
        } catch (\Exception $ex) {
            return json(EsUtils::stdmessage(0, $ex->getMessage()));
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        if (!is_numeric($id)) {
            return json(EsUtils::stdmessage(0, 'id值无效', $id));
        }
        if ($id > 0) {
            $model = EcSpecificationModel::find($id);
            if (!$model) {
                return json(EsUtils::stdmessage(0, '记录不存在'));
            }
        } else {
            $model = new EcSpecificationModel();
            $model->sort = 999;
            $model->status = 1;
            $model->category_id = 0;
        }
        $data = [
            'data' => $model,
            'status_data' => $model->getStatusDataAttr(),
            'pid_data' => EcSpecificationModel::getDictData($model->category_id),
            'category_id_data' => EcCategoryModel::getDictData(),
        ];
        return json(EsUtils::stdmessage(1, $id, $data));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $formData = $request->all();
        $validator = Validate::rule([
            'pid' => 'required|numeric',
            'category_name' => 'required|max:150',
            'icon' => 'max:150',
        ], [
            'required' => ':attribute 必须填写',
            'numeric' => ':attribute 必须是数值',
            'max' => ':attribute 不能超过 :max 个字符',
        ], [
            'pid' => '上级类别',
            'category_name' => '类别名称',
            'icon' => '类别图片'
        ]);
        if (!$validator->check($formData)) {
        return json(EsUtils::stdmessage(0, $validator->getError()));
}
        try {
            $affected = EcSpecificationModel::where('id', $id)->update($formData);
            return json(EsUtils::stdmessage(1, '', $affected));
        } catch (\Exception $ex) {
            return json(EsUtils::stdmessage(0, $ex->getMessage()));
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        try {
            $affected = EcSpecificationModel::destroy($id);
            ModelUtils::cacheRefresh('ec_specification');
            return json(EsUtils::stdmessage(1, '', $affected));
        } catch (\Exception $ex) {
            return json(EsUtils::stdmessage(0, $ex->getMessage()));
        }
    }
}
